package org.apache.struts.pharmacy.pharmacy.action;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.struts.pharmacy.pharmacy.action.SearchResultsAction;
import org.apache.struts.pharmacy.pharmacy.model.*;

import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.v251.message.TBR_R08;
import ca.uhn.hl7v2.parser.EncodingNotSupportedException;
import ca.uhn.hl7v2.parser.PipeParser;

import com.earogya.communicate.Communicator;
import com.earogya.logic.pharmacy.request.CreateEQQQ04;
import com.earogya.logic.pharmacy.request.TBR_R08_Handler;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class DrugsGivenToPatientAction extends ActionSupport{
	
	private PrescriptionDrugs prescriptionDrugs;
	private List<DrugsGivenToPatient> drugsGivenToPatient;
	private HL7Message message;
	private Date date;
	private SearchResultsAction action;
	
	public HL7Message getMessage() {
		return message;
	}

	public PrescriptionDrugs getPrescriptionDrugs() {
		return prescriptionDrugs;
	}

	public void setPrescriptionDrugs(PrescriptionDrugs prescriptionDrugs) {
		this.prescriptionDrugs = prescriptionDrugs;
	}

	public SearchResultsAction getAction() {
		return action;
	}

	public void setAction(SearchResultsAction action) {
		this.action = action;
	}

	public String execute() throws Exception {
		Map<String, Object> session=ActionContext.getContext().getSession();
		CreateEQQQ04 createMessage=new CreateEQQQ04(prescriptionDrugs);
		String msg=createMessage.createMessage((String)session.get("facility"));
		message=new HL7Message();
		if(!msg.equals(null)){
			Communicator c=new Communicator();
			String reply=c.sendMessage(msg);
			message.setMessage(msg+"-------------"+reply);
			TBR_R08_Handler hh =new TBR_R08_Handler(createTBR_R08Msg(reply.toString()));
			drugsGivenToPatient = hh.manageMessage();
		}
		else{
			message.setMessage("empty");
		}
		return SUCCESS;
	}
	
	
	
	public List<DrugsGivenToPatient> getDrugsGivenToPatient() {
		return drugsGivenToPatient;
	}

	public void setDrugsGivenToPatient(List<DrugsGivenToPatient> drugsGivenToPatient) {
		this.drugsGivenToPatient = drugsGivenToPatient;
	}

	public void validate(){
		if(prescriptionDrugs.getPatientId().length()== 0){
			addFieldError( "prescriptionDrugs.patientId", "Patient ID required" );
		}
	}
	
	public TBR_R08 createTBR_R08Msg(String message) throws EncodingNotSupportedException, HL7Exception{
		Message hapiMsg  = new PipeParser().parse(message);
		return (TBR_R08)hapiMsg;
	}
}
